import React from 'react';
import {
  BrowserRouter as Router,
  Route,
  Link,
  Routes
} from 'react-router-dom';
import SubmitInfo from './SubmitInfo';
import ListInfo from './ListInfo';
import axios from 'axios';

const instance = axios.create();
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { address: '', random: '' };
  }
  componentDidMount() {
    console.log('start to listen');
    // instance.post('/getRandom').then(res => {
    //   console.log(res);
    //   this.setState({ 'random': res });
    // }).catch(error => {
    //   console.log(error);
    // })
    window.ethereum.request({ method: 'eth_requestAccounts' }).then((accounts) => {
      console.log(accounts);
      this.setState({ 'address': accounts[0] });
    });
  }
  // changeChain(chainId) {
  //   this.setState({ chain: chainId });
  // }
  render() {
    if (typeof window.ethereum === 'undefined') {
      return <h1>请先安装metamask插件</h1>
    }
    if (this.state.address === '') {
      return <h1>正在连接到metamask...</h1>
    }
    // if (this.state.random === '') {
    //   return <h1>'正在连接到ca...'</h1>
    // }
    return (
      <div>
        <Router>
          <div>
            <nav>
              <h1>logined eth address:{this.state.address}</h1>
              <ul>
                {/* <li>
                  <Link to='/login'>login</Link>
                </li> */}
                < li >
                  <Link to='/submitInfo'>submit info</Link>
                </li>
                <li>
                  <Link to='/listInfo'>list info</Link>
                </li>
              </ul>
            </nav>

            {/* A <Switch> looks through its children <Route>s and
            renders the first one that matches the current URL. */}
            <Routes>
              <Route path='/' element={<h1>hello</h1>} />
              <Route path='/submitInfo' element={<SubmitInfo address={this.state.address} axios={instance} />} />
              <Route path='/listInfo' element={<ListInfo address={this.state.address} axios={instance} />} />
            </Routes>
          </div>
        </Router >
      </div >
    );
  }
}
export default App;
